package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.entity.PoliticalReview;
import org.example.demo.entity.User;
import org.example.demo.service.PoliticalReviewService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.ReturnMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("political/review")
public class PoliticalReviewController {

    @Resource
    private PoliticalReviewService politicalReviewService;

    @Resource
    private UserService userService;

    // 分页查询政审表列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody PoliticalReview review,
                                 @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {
//        ReturnMap returnMap = new ReturnMap();
        Page<PoliticalReview> page = new Page<>(pageNum, pageSize);

        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(review.getNickName()!=null&&!review.getNickName().isEmpty(),User::getName,review.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        Map<String, Object> map = new HashMap<>();
        if (!userMap.isEmpty()) {
            // 批量查询用户信息
            QueryWrapper<PoliticalReview> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(review.getUserId() != null && review.getUserId() != 0L, PoliticalReview::getUserId, review.getUserId())
                    .in(PoliticalReview::getUserId, userMap.keySet())
                    .orderByDesc(PoliticalReview::getCreateTime);
            Page<PoliticalReview> result = politicalReviewService.page(page, queryWrapper);
            // 遍历结果集，设置用户昵称
            for (PoliticalReview politicalReview : result.getRecords()) {
                User user = userMap.get(politicalReview.getUserId());
                if (user != null) {
                    politicalReview.setNickName(user.getName());
                }
            }
            map.put("page", result);
//            returnMap.setData("page", result);
        }else{
            map.put("page", new ArrayList<>());
        }


        return AjaxResult.success(map);
    }

    // 查询政审表详情
    @GetMapping("detail")
    public AjaxResult detail(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();

        PoliticalReview review = politicalReviewService.getById(id);
//        returnMap.setData("review", review);

        Map map = new HashMap<>();
        map.put("review", review);
        return AjaxResult.success(map);
    }

    // 提交政审表
    @PostMapping("submit")
    public AjaxResult submit(@RequestBody PoliticalReview review) {
//        ReturnMap returnMap = new ReturnMap();

        if (review.getId() != null) {
            review.setUpdateTime(LocalDateTime.now());
            politicalReviewService.updateById(review);
        } else {
            review.setCreateTime(LocalDateTime.now());
            review.setUpdateTime(LocalDateTime.now());
            politicalReviewService.save(review);
        }

//        returnMap.setReturnCode(200);
        return AjaxResult.success();
    }


    // 获取申请人最新政审表
    @GetMapping("latestByApplicant")
    public AjaxResult getLatestByApplicant(@RequestParam Integer applicantId) {
//        ReturnMap returnMap = new ReturnMap();

        QueryWrapper<PoliticalReview> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PoliticalReview::getUserId, applicantId)
                .orderByDesc(PoliticalReview::getCreateTime)
                .last("LIMIT 1");

        PoliticalReview review = politicalReviewService.getOne(queryWrapper);
//        returnMap.setData("review", review);

        Map<String, Object> map = new HashMap<>();
        return AjaxResult.success(map);
    }

    // 删除政审表
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        boolean success = politicalReviewService.removeById(id);

        if (success) return AjaxResult.success();
        return AjaxResult.error();
//        returnMap.setReturnCode(success ? 200 : 405);
//        return returnMap.getreturnMap();
    }

    // 查询总数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody PoliticalReview review) {
//        ReturnMap returnMap = new ReturnMap();
        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(review.getNickName() != null && !review.getNickName().isEmpty(), User::getName, review.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        Map<String, Object> map = new HashMap<>();
        if (!userMap.isEmpty()) {
            QueryWrapper<PoliticalReview> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(PoliticalReview::getUserId, userMap.keySet())
                    .eq(review.getUserId() != null && review.getUserId() != 0L, PoliticalReview::getUserId, review.getUserId());

            int count = politicalReviewService.count(queryWrapper);
//            returnMap.setData("count", count);
            map.put("count", count);
        } else {
            map.put("count", 0);
//            returnMap.setData("count", 0);
        }

        return AjaxResult.success(map);
//        return returnMap.getreturnMap();
    }
}
